package com.wpre.lotterysystem.common.pojo;

import com.wpre.lotterysystem.common.errcode.ErrorCode;
import com.wpre.lotterysystem.common.errcode.GlobalErrorCodeConstants;
import lombok.Data;
import org.springframework.util.Assert;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA.
 * Description: 统一返回结果
 * User: LianBao
 * Date: 2024-12-10
 * Time: 20:08
 */
@Data
//为了能够进行各种协议的序列化,所以implements Serializable
public class CommonResult<T> implements Serializable {

    /**
     * 返回的错误码
     */
    private Integer code;

    /**
     * 正常返回的数据,使用泛型
     */
    private T data;

    /**
     * 错误码描述
     */
    private String msg;

    //成功
    public static <T> CommonResult<T> success(T data) {
        CommonResult<T> result = new CommonResult<>();
        result.code = GlobalErrorCodeConstants.SUCCESS.getCode();
        result.data = data;
        result.msg = "";
        return result;
    }

    //失败
    public static <T> CommonResult<T> error(Integer code, String msg) {
        //断言,如果错误码不等于200才往下走
        Assert.isTrue(!GlobalErrorCodeConstants.SUCCESS.getCode().equals(code), "不是错误的异常");
        CommonResult<T> result = new CommonResult<>();
        result.code = code;
        result.msg = msg;
        return result;
    }

    //根据Error设置错误码
    public static <T> CommonResult<T> error(ErrorCode errorCode) {
        return error(errorCode.getCode(), errorCode.getMsg());
    }


}
